package xworker.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

import java.io.IOException;

public class NettyActions {
	public static NettySession getNettySession(ActionContext actionContext) {
		ChannelHandlerContext ctx = actionContext.getObject("ctx");
		return NettySession.getSession(ctx.channel());
	}
	
	public static NettySessionManager getNettySessionManager(ActionContext actionContext) {
		ChannelHandlerContext ctx = actionContext.getObject("ctx");
		return NettySession.getSession(ctx.channel()).getSessionManager();
	}
	
	public static void sendMessageToSession(ActionContext actionContext) throws IOException {
		Thing self = actionContext.getObject("self");
		
		ChannelHandlerContext ctx = actionContext.getObject("ctx");
		NettySessionManager sessionManager = NettySession.getSession(ctx.channel()).getSessionManager();
		String sessionId = self.doAction("getSessionId", actionContext);
		Object message = self.doAction("getMessage", actionContext);
		sessionManager.sendMessage(sessionId, message);
	}
	
	public static void sendMessageToGroup(ActionContext actionContext) throws IOException {
		Thing self = actionContext.getObject("self");

		ChannelHandlerContext ctx = actionContext.getObject("ctx");

		NettySessionManager sessionManager = NettySession.getSession(ctx.channel()).getSessionManager();
		String groupPath = self.doAction("getGroupPath", actionContext);
		Object message = self.doAction("getMessage", actionContext);
		sessionManager.sendMessageToGroup(groupPath, message);
	}

	//xworker.netty.NettyActions/@WriteAndFlush/@actions/@run
	public static ChannelFuture writeAndFlush(ActionContext actionContext){
		Thing self = actionContext.getObject("self");
		ChannelHandlerContext ctx = actionContext.getObject("ctx");

		Object msg = self.doAction("getMessage", actionContext);
		String listener = self.doAction("getListener", actionContext);
		ChannelFuture future = ctx.channel().writeAndFlush(msg);
		if("CLOSE".equals(listener)){
			future.addListener(ChannelFutureListener.CLOSE);
		}else if("CLOSE_ON_FAILURE".equals(listener)){
			future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
		}else if("FIRE_EXCEPTION_ON_FAILURE".equals(listener)){
			future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
		}
   	    return future;
	}

	//xworker.netty.NettyActions/@GetNettyClient/@actions/@run
	public static NettyClient getNettyClient(ActionContext actionContext){
		Thing self = actionContext.getObject("self");
		Thing thing = self.doAction("getNettyClient", actionContext);
		return thing != null ? NettyClient.getNettyClient(thing, actionContext) : null;
	}
}
